#include "UsrAI.h"
#include <iostream>
#include <algorithm>
#include <ctime>
#include <sstream>
#include <unordered_set>
#include <string>
#include <climits>
#include <cmath>

#define ACTION_OK 0
#define BLOCKSIDELENGTH 35.7

using namespace std;

// 初始化静态变量
tagGame tagUsrGame;
ins UsrIns;
tagInfo UsrAI::prevInfo;
int UsrAI::center_x = 0;
int UsrAI::center_y = 0;
bool UsrAI::centerInitialized = false;
set<pair<int, int>> UsrAI::occupiedPositions;
time_t UsrAI::startTime = time(nullptr);
int UsrAI::houseCount = 0;
int UsrAI::housesUnderConstruction = 0;
UsrAI::GameStage UsrAI::currentStage = UsrAI::STAGE_INITIAL;
int UsrAI::searchRadius = 1;
int UsrAI::lastHouseX = -1;
int UsrAI::lastHouseY = -1;

// 人口增长系统
int UsrAI::targetPopulation = 0;
time_t UsrAI::lastVillagerProductionTime = time(nullptr);

// 新增静态变量
bool UsrAI::stockBuilt = false;
bool UsrAI::dockBuilt = false;
bool UsrAI::fishingBoatBuilt = false;
bool UsrAI::ageUpgraded = false;
bool UsrAI::villagersAssigned = false;

// 初始化市镇中心位置
void UsrAI::initializeCenter(const tagInfo& info) {
    for (const auto& building : info.buildings) {
        if (building.Type == BUILDING_CENTER) {
            center_x = building.BlockDR;
            center_y = building.BlockUR;
            centerInitialized = true;
            DebugText("市镇中心位于 (" + to_string(center_x) + "," + to_string(center_y) + ")");

            // 标记市镇中心占用位置
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    occupiedPositions.insert({center_x + i, center_y + j});
                }
            }

            currentStage = STAGE_BUILD_HOUSES;
            break;
        }
    }
}

// 检查位置是否适合建造（通用函数）
bool UsrAI::isPositionValidForBuilding(int x, int y, int width, int height, const tagInfo& info) {
    // 检查指定区域
    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            int checkX = x + i;
            int checkY = y + j;

            // 边界检查
            if (checkX < 0 || checkY < 0 || checkX >= 128 || checkY >= 128)
                return false;

            // 地形检查
            if ((*info.theMap)[checkX][checkY].type != MAPPATTERN_GRASS ||
                (*info.theMap)[checkX][checkY].height == -1)
                return false;

            // 位置占用检查
            if (occupiedPositions.find({checkX, checkY}) != occupiedPositions.end())
                return false;

            // 建筑冲突检查
            for (const auto& b : info.buildings) {
                if (b.BlockDR == checkX && b.BlockUR == checkY)
                    return false;
            }

            // 资源冲突检查
            for (const auto& res : info.resources) {
                if (res.BlockDR == checkX && res.BlockUR == checkY)
                    return false;
            }
        }
    }
    return true;
}

// 检查位置是否适合建造房屋（兼容旧调用）
bool UsrAI::isPositionValidForHouse(int x, int y, const tagInfo& info) {
    return isPositionValidForBuilding(x, y, 2, 2, info);
}

// 寻找海岸位置建造船坞
bool UsrAI::findCoastalPosition(int& x, int& y, const tagInfo& info) {
    // 从中心向外螺旋搜索
    for (int r = 1; r <= 20; r++) {
        // 检查四个方向
        vector<pair<int, int>> directions = {
            {center_x + r, center_y},
            {center_x - r, center_y},
            {center_x, center_y + r},
            {center_x, center_y - r}
        };

        for (const auto& pos : directions) {
            int checkX = pos.first;
            int checkY = pos.second;

            // 检查是否靠海
            bool nearOcean = false;
            for (int dx = -1; dx <= 1; dx++) {
                for (int dy = -1; dy <= 1; dy++) {
                    int oceanX = checkX + dx;
                    int oceanY = checkY + dy;
                    if (oceanX >= 0 && oceanY >= 0 && oceanX < 128 && oceanY < 128) {
                        if ((*info.theMap)[oceanX][oceanY].type == MAPPATTERN_OCEAN) {
                            nearOcean = true;
                            break;
                        }
                    }
                }
                if (nearOcean) break;
            }

            if (nearOcean && isPositionValidForBuilding(checkX, checkY, 2, 2, info)) {
                x = checkX;
                y = checkY;
                return true;
            }
        }
    }
    return false;
}

void UsrAI::assignTasksToVillagers(const tagInfo& info) {
    // 统计各任务类型村民数量
    int woodWorkers = 0;
    int foodWorkers = 0;
    int buildWorkers = 0;

    // 统计当前任务分配情况
    for (const auto& farmer : info.farmers) {
        if (farmer.FarmerSort != 0) continue; // 只统计陆地村民

        if (farmer.NowState == HUMAN_STATE_WORKING) {
            // 检查工作目标类型
            for (const auto& res : info.resources) {
                if (res.SN == farmer.WorkObjectSN) {
                    if (res.Type == RESOURCE_TREE) {
                        woodWorkers++;
                    } else if (res.Type == RESOURCE_GAZELLE ||
                               res.Type == RESOURCE_ELEPHANT ||
                               res.Type == RESOURCE_FISH) {
                        foodWorkers++;
                    }
                    break;
                }
            }
        } else if (farmer.NowState == HUMAN_STATE_WALKING) {
            // 检查行走目标是否是建筑位置
            if (farmer.DR0 > 0 || farmer.UR0 > 0) {
                buildWorkers++;
            }
        }
    }

    DebugText("任务统计: 伐木=" + to_string(woodWorkers) +
              " 食物=" + to_string(foodWorkers) +
              " 建造=" + to_string(buildWorkers));

    // 分配空闲村民
    for (const auto& farmer : info.farmers) {
        if (farmer.FarmerSort != 0 || farmer.NowState != HUMAN_STATE_IDLE)
            continue;

        // 优先补充伐木村民
        if (woodWorkers < 2) {
            int targetTreeSN = findNearestResource(farmer, RESOURCE_TREE, info);
            if (targetTreeSN != -1) {
                int ret = HumanAction(farmer.SN, targetTreeSN);
                if (ret > 0) {
                    DebugText("村民 #" + to_string(farmer.SN) + " 分配砍树");
                    woodWorkers++;
                    continue;
                }
            }
        }

        // 补充食物采集村民
        if (foodWorkers < 2) {
            int targetFoodSN = findNearestResource(farmer, RESOURCE_GAZELLE, info);
            if (targetFoodSN == -1) {
                targetFoodSN = findNearestResource(farmer, RESOURCE_ELEPHANT, info);
            }
            if (targetFoodSN == -1) {
                targetFoodSN = findNearestResource(farmer, RESOURCE_FISH, info);
            }

            if (targetFoodSN != -1) {
                int ret = HumanAction(farmer.SN, targetFoodSN);
                if (ret > 0) {
                    DebugText("村民 #" + to_string(farmer.SN) + " 分配采集食物");
                    foodWorkers++;
                    continue;
                }
            }
        }

        // 建造船坞
        if (!dockBuilt && buildWorkers == 0 && info.Wood >= BUILD_DOCK_WOOD) {
            int dockX, dockY;
            if (findCoastalPosition(dockX, dockY, info)) {
                int ret = HumanBuild(farmer.SN, BUILDING_DOCK, dockX, dockY);
                if (ret > 0) {
                    DebugText("村民 #" + to_string(farmer.SN) + " 建造船坞");
                    // 标记占用位置
                    for (int i = 0; i < 2; i++) {
                        for (int j = 0; j < 2; j++) {
                            occupiedPositions.insert({dockX+i, dockY+j});
                        }
                    }
                    buildWorkers++;
                    continue;
                }
            }
        }

        // 建造仓库
        if (!stockBuilt && buildWorkers == 0 && info.Wood >= BUILD_STOCK_WOOD) {
            int stockX, stockY;
            if (findNearbyPosition(stockX, stockY, info)) {
                int ret = HumanBuild(farmer.SN, BUILDING_STOCK, stockX, stockY);
                if (ret > 0) {
                    DebugText("村民 #" + to_string(farmer.SN) + " 建造仓库");
                    // 标记占用位置
                    for (int i = 0; i < 3; i++) {
                        for (int j = 0; j < 3; j++) {
                            occupiedPositions.insert({stockX+i, stockY+j});
                        }
                    }
                    buildWorkers++;
                    continue;
                }
            }
        }

        // 默认分配采集食物
        int targetFoodSN = findNearestResource(farmer, RESOURCE_GAZELLE, info);
        if (targetFoodSN == -1) {
            targetFoodSN = findNearestResource(farmer, RESOURCE_ELEPHANT, info);
        }
        if (targetFoodSN == -1) {
            targetFoodSN = findNearestResource(farmer, RESOURCE_FISH, info);
        }

        if (targetFoodSN != -1) {
            int ret = HumanAction(farmer.SN, targetFoodSN);
            if (ret > 0) {
                DebugText("村民 #" + to_string(farmer.SN) + " 分配采集食物");
                foodWorkers++;
            }
        }
    }
}

// 寻找附近的建造位置
bool UsrAI::findNearbyPosition(int& x, int& y, const tagInfo& info) {
    // 如果有上一个房屋位置，从那里开始搜索
    int startX = (lastHouseX != -1) ? lastHouseX : center_x;
    int startY = (lastHouseY != -1) ? lastHouseY : center_y;

    // 搜索模式: 从中心向外螺旋搜索
    for (int r = 1; r <= searchRadius; r++) {
        // 检查四个方向
        vector<pair<int, int>> directions = {
            {startX + r, startY},  // 右
            {startX - r, startY},  // 左
            {startX, startY + r},  // 上
            {startX, startY - r}   // 下
        };

        // 随机打乱方向以避免偏向
        random_shuffle(directions.begin(), directions.end());

        for (const auto& pos : directions) {
            int checkX = pos.first;
            int checkY = pos.second;

            if (isPositionValidForHouse(checkX, checkY, info)) {
                x = checkX;
                y = checkY;
                lastHouseX = checkX;
                lastHouseY = checkY;
                return true;
            }
        }
    }

    // 扩大搜索半径
    if (searchRadius < 20) {
        searchRadius++;
        DebugText("扩大搜索半径至: " + to_string(searchRadius));
    }

    return false;
}

// 房屋建造阶段
void UsrAI::buildHousesPhase(const tagInfo& info) {
    // 状态显示
    string status = "房屋建造阶段 | ";
    status += "目标: " + to_string(TARGET_HOUSES) + " | ";
    status += "完成: " + to_string(houseCount) + " | ";
    status += "建造中: " + to_string(housesUnderConstruction);
    DebugText(status);

    // 检查是否完成目标
    if (houseCount >= TARGET_HOUSES) {
        // 目标人口设置为12个村民
        targetPopulation = 12;
        currentStage = STAGE_POPULATION_GROWTH;
        DebugText("=== 进入人口增长阶段 ===");
        DebugText("目标人口: " + to_string(targetPopulation));
        return;
    }

    // 尝试建造新房屋
    if (housesUnderConstruction < TARGET_HOUSES - houseCount) {
        int buildX, buildY;
        if (findNearbyPosition(buildX, buildY, info)) {
            // 检查木材是否足够
            if (info.Wood >= BUILD_HOUSE_WOOD) {
                for (const auto& farmer : info.farmers) {
                    if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 0) {
                        int ret = HumanBuild(farmer.SN, BUILDING_HOME, buildX, buildY);
                        if (ret > 0) {
                            DebugText("村民 #" + to_string(farmer.SN) + " 建造房屋于 " +
                                      to_string(buildX) + "," + to_string(buildY));

                            housesUnderConstruction++;

                            // 标记占用位置
                            for (int i = 0; i < 2; i++) {
                                for (int j = 0; j < 2; j++) {
                                    occupiedPositions.insert({buildX+i, buildY+j});
                                }
                            }
                        } else {
                            DebugText("建造失败: " + to_string(ret) + " 位置: " +
                                      to_string(buildX) + "," + to_string(buildY));
                        }
                        break;
                    }
                }
            } else {
                DebugText("木材不足，需要 " + to_string(BUILD_HOUSE_WOOD) + " 木材");
            }
        } else {
            DebugText("正在搜索附近可用位置...");
        }
    }
}

// 人口增长阶段


// 生产村民
void UsrAI::produceVillagers(const tagInfo& info) {
    // 检查冷却时间（避免每帧都尝试生产）
    time_t currentTime = time(nullptr);
    if (difftime(currentTime, lastVillagerProductionTime) < 5) {
        return;
    }
    lastVillagerProductionTime = currentTime;

    // 查找市镇中心
    for (const auto& building : info.buildings) {
        if (building.Type == BUILDING_CENTER) {
            // 检查市镇中心是否空闲
            if (building.Project == 0) {
                // 检查食物是否足够
                if (info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD) {
                    // 检查人口是否未满
                    int currentPopulation = info.farmers.size() + info.armies.size();
                    if (currentPopulation < info.Human_MaxNum) {
                        // 生产村民
                        int ret = BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);
                        if (ret > 0) {
                            DebugText("市镇中心生产村民中...");
                        } else {
                            DebugText("生产村民失败: " + to_string(ret));
                        }
                    } else {
                        DebugText("人口已满，无法生产更多村民");
                    }
                } else {
                    DebugText("食物不足，需要 " + to_string(BUILDING_CENTER_CREATEFARMER_FOOD) + " 食物");
                }
            } else {
                DebugText("市镇中心忙碌中...");
            }
            break; // 只需要处理一个市镇中心
        }
    }
}

int UsrAI::findNearestResource(const tagFarmer& farmer, int resourceType, const tagInfo& info) {
    int targetSN = -1;
    int minDistance = INT_MAX;

    for (const auto& res : info.resources) {
        if (res.Type == resourceType && res.Cnt > 0) {
            int distance = abs(res.BlockDR - farmer.BlockDR) +
                          abs(res.BlockUR - farmer.BlockUR);
            if (distance < minDistance) {
                minDistance = distance;
                targetSN = res.SN;
            }
        }
    }

    return targetSN;
}

// 资源收集阶段
void UsrAI::collectResourcesPhase(const tagInfo& info) {
    // 状态显示
    DebugText("资源收集阶段 | 木材: " + to_string(info.Wood) +
              " | 食物: " + to_string(info.Meat) +
              " | 村民: " + to_string(info.farmers.size()));

    // 分配任务给空闲村民
    assignTasksToVillagers(info);
}

// 人口增长阶段（添加资源收集）
void UsrAI::populationGrowthPhase(const tagInfo& info) {
    // 计算当前人口
    int currentPopulation = info.farmers.size() + info.armies.size();
    int populationCapacity = info.Human_MaxNum;

    // 状态显示
    string status = "人口增长阶段 | ";
    status += "当前: " + to_string(currentPopulation) + "/" + to_string(populationCapacity);
    status += " | 目标: " + to_string(targetPopulation);
    DebugText(status);

    // 检查是否达到目标人口
    if (currentPopulation >= targetPopulation) {
        currentStage = STAGE_COLLECT_RESOURCES;
        DebugText("=== 进入资源收集阶段 ===");
        return;
    }

    // 生产村民
    produceVillagers(info);

    // 关键修改：确保空闲村民被分配任务
    // 添加任务分配逻辑，确保村民不会闲置
    assignTasksToVillagers(info);
}
// 建造必要建筑阶段（仓库和船坞）
void UsrAI::buildRequiredBuildingsPhase(const tagInfo& info) {
    // 更新建筑状态
    stockBuilt = false;
    dockBuilt = false;
    for (const auto& b : info.buildings) {
        if (b.Type == BUILDING_STOCK && b.Percent == 100) stockBuilt = true;
        if (b.Type == BUILDING_DOCK && b.Percent == 100) dockBuilt = true;
    }

    DebugText("建造必要建筑阶段 | 仓库: " + string(stockBuilt ? "完成" : "未完成") +
              " | 船坞: " + string(dockBuilt ? "完成" : "未完成"));

    // 如果都建造完成，进入下一阶段
    if (stockBuilt && dockBuilt) {
        currentStage = STAGE_UPGRADE_AGE;
        DebugText("=== 进入升级时代阶段 ===");
        return;
    }

    // 尝试建造仓库
    if (!stockBuilt) {
        int buildX, buildY;
        if (findNearbyPosition(buildX, buildY, info)) {
            if (info.Wood >= BUILD_STOCK_WOOD) {
                for (const auto& farmer : info.farmers) {
                    if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 0) {
                        int ret = HumanBuild(farmer.SN, BUILDING_STOCK, buildX, buildY);
                        if (ret > 0) {
                            DebugText("村民 #" + to_string(farmer.SN) + " 建造仓库于 " +
                                      to_string(buildX) + "," + to_string(buildY));

                            // 标记占用位置（仓库3x3）
                            for (int i = 0; i < 3; i++) {
                                for (int j = 0; j < 3; j++) {
                                    occupiedPositions.insert({buildX+i, buildY+j});
                                }
                            }
                        }
                        break;
                    }
                }
            } else {
                DebugText("木材不足，需要 " + to_string(BUILD_STOCK_WOOD) + " 木材建造仓库");
            }
        }
    }

    // 尝试建造船坞
    if (!dockBuilt) {
        int dockX, dockY;
        if (findCoastalPosition(dockX, dockY, info)) {
            if (info.Wood >= BUILD_DOCK_WOOD) {
                for (const auto& farmer : info.farmers) {
                    if (farmer.NowState == HUMAN_STATE_IDLE && farmer.FarmerSort == 0) {
                        int ret = HumanBuild(farmer.SN, BUILDING_DOCK, dockX, dockY);
                        if (ret > 0) {
                            DebugText("村民 #" + to_string(farmer.SN) + " 建造船坞于 " +
                                      to_string(dockX) + "," + to_string(dockY));

                            // 标记占用位置（船坞2x2）
                            for (int i = 0; i < 2; i++) {
                                for (int j = 0; j < 2; j++) {
                                    occupiedPositions.insert({dockX+i, dockY+j});
                                }
                            }
                        }
                        break;
                    }
                }
            } else {
                DebugText("木材不足，需要 " + to_string(BUILD_DOCK_WOOD) + " 木材建造船坞");
            }
        } else {
            DebugText("正在寻找海岸位置建造船坞...");
        }
    }
}

// 升级时代阶段
void UsrAI::upgradeAgePhase(const tagInfo& info) {
    // 检查是否已经升级
    if (info.civilizationStage == CIVILIZATION_TOOLAGE) {
        ageUpgraded = true;
        currentStage = STAGE_BUILD_FISHING_BOAT;
        DebugText("=== 时代升级完成，进入生产渔船阶段 ===");
        return;
    }

    DebugText("升级时代阶段 | 需要500食物");

    // 检查食物是否足够
    if (info.Meat >= 500) {
        // 找到市镇中心
        for (const auto& building : info.buildings) {
            if (building.Type == BUILDING_CENTER && building.Project == 0) {
                int ret = BuildingAction(building.SN, BUILDING_CENTER_UPGRADE);
                if (ret > 0) {
                    DebugText("市镇中心开始升级时代");
                }
                break;
            }
        }
    } else {
        DebugText("食物不足，需要500食物升级时代");
    }
}

// 生产渔船阶段
void UsrAI::buildFishingBoatPhase(const tagInfo& info) {
    // 检查是否已经生产渔船
    if (fishingBoatBuilt) {
        DebugText("=== 所有任务完成 ===");
        return;
    }

    DebugText("生产渔船阶段 | 需要60木材");

    // 检查木材是否足够
    if (info.Wood >= 60) {
        // 找到船坞
        for (const auto& building : info.buildings) {
            if (building.Type == BUILDING_DOCK && building.Project == 0) {
                int ret = BuildingAction(building.SN, BUILDING_DOCK_CREATE_SAILING);
                if (ret > 0) {
                    DebugText("船坞开始生产渔船");
                    fishingBoatBuilt = true;
                }
                break;
            }
        }
    } else {
        DebugText("木材不足，需要60木材生产渔船");
    }
}

// 主处理函数
void UsrAI::processData() {
    tagInfo info = getInfo();

    // 更新房屋状态
    houseCount = 0;
    housesUnderConstruction = 0;
    for (const auto& b : info.buildings) {
        if (b.Type == BUILDING_HOME) {
            if (b.Percent == 100) houseCount++;
            else housesUnderConstruction++;
        }
    }

    // 游戏阶段处理
    switch(currentStage) {
        case STAGE_INITIAL:
            if (!centerInitialized) initializeCenter(info);
            break;

        case STAGE_BUILD_HOUSES:
            buildHousesPhase(info);
            break;

        case STAGE_POPULATION_GROWTH:
            populationGrowthPhase(info);
            break;

        case STAGE_COLLECT_RESOURCES:
            collectResourcesPhase(info);
            break;

        case STAGE_BUILD_REQUIRED_BUILDINGS:  // 新增阶段
            buildRequiredBuildingsPhase(info);
            break;

        case STAGE_UPGRADE_AGE:               // 新增阶段
            upgradeAgePhase(info);
            break;

        case STAGE_BUILD_FISHING_BOAT:        // 新增阶段
            buildFishingBoatPhase(info);
            break;
    }

    // 检查超时（5分钟=300秒）
    time_t currentTime = time(nullptr);
    if (difftime(currentTime, startTime) > 300) {
        DebugText("!!! 超时警告: 5分钟时间已到 !!!");
    }

    prevInfo = info;
}
